package com.fiberhome.opticalbox.ui.keyboard810;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import android.widget.Toast;

import com.amlapp.android.RemoteClient.RemoteClient;
import com.amlapp.android.RemoteClient.SendThread;
import com.amlapp.android.RemoteClient.Service;
import com.fiberhome.opticalbox.R;

public class RemoteControl extends BaseRCActivity {
	private RemoteClient mRemoteClient = null;
	public static Service mService = null;
	private TextView textView;
	
	

	@Override
	public void onCreate(Bundle savedInstanceState) {
		setHandler(connectHandler);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ob_activity_remote);
		textView = (TextView)findViewById(R.id.textView);
		mRemoteClient = RemoteClient.getinstance();
		mRemoteClient.UdpInit();
		connectService();
	}

	public void connectService() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				String ip = "192.168.8.255";
				mRemoteClient.UdpIpsend(ip);
				Service service = new Service(ip, "", null, Service.TRUE);
				connectService(service);
			}
		}).start();
	}

	public void connectService(Service service) {
		String text = textView.getText().toString();
		text = text + "\n";
		textView.setText(text + "sendCmdMessage[cmd:CMD_CONNECT]");
		
		mService = service;
		sendCmdMessage(SendThread.CMD_CONNECT, 0, 0, mService);
	}
	
	@SuppressLint("HandlerLeak")
	private Handler connectHandler = new Handler() {
		public void handleMessage(Message msg) {
			String text = textView.getText().toString();
			text = text + "\n";
			textView.setText(text + "connectHandler handleMessage");
			switch (msg.what) {
			case SendThread.CMD_CONNECT:
				 Service service = (Service) msg.obj;
				
				String text1 = textView.getText().toString();
				text1 = text1 + "\n";
				textView.setText(text1 + "CONNECT successful ? service :! "+service.getConnected()+"!");
				
				Toast.makeText(getApplicationContext(), "CMD CONNECT", Toast.LENGTH_SHORT).show();
				
				
//				sendTestMessage();
				break;
			}
			super.handleMessage(msg);
		}
	};
	
	Handler handler = new Handler();
	
//	private int  testTime = 10;
//	
//	private void sendTestMessage(){
//		testTime -- ;
//		if(testTime > 0){
//			handler.postDelayed(new Runnable() {
//				@Override
//				public void run() {
//					Integer right = getResources().getInteger(R.integer.ob_keycode_right);
//					sendCmdMessage(SendThread.CMD_SEND_KEY, 0, 0,  new Key(RemoteIME.mService,MotionEvent.ACTION_DOWN,
//							right ));
//					
//					sendTestMessage();
//					Toast.makeText(getApplicationContext(), "Sending Message keycode_value("+right+"[right])("+testTime+")", Toast.LENGTH_SHORT).show();
//				}
//			}, 3000);
//		}
//	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (mRemoteClient != null){
			mRemoteClient.UdpClose();
		}
	}

}